/******************************************************************************/
/* CRA Analysis                                                        */
/******************************************************************************/
	
local Data "CRA_Analysis"

noi disp "Obtaining bank financial data for bank-level regressions..."
noi disp "Verifying that `Data'.dta does not already exist..."
* This returns an error if the file does not exist.
capture confirm file "`Data'.dta"

* If an error is returned, then the commands below are run.
if _rc == 601 {
	noi disp "Data not found.  Building data..."
	noi disp "Building `Data'.dta..."


quietly{
noi disp "Loading CRA.dta..."
insheet using "$SourceData\cra_rssd_v3.csv", clear
save "$LocalData\\CRA_d3.dta", replace
use "$LocalData\\CRA_d3.dta", clear

gen year = year(date(date,"YMD"))
gen geography = 1000*state+county
sort cert year

merge m:1 cert year using "$SourceData\RIS.dta"
drop _merge

sort geography year


merge m:1 geography year using "$LocalData\BartikAnalyticData_2digit.dta"
	gen temp = cpi if year==2001
	egen base = max(temp)
	drop temp

	gen cpi_adj = cpi/base
	gen asset2 = asset/cpi_adj

*Aggregating across size categories (<100, 100-250, 250-1000)
egen sblt250k = rowtotal(amountless100 amount100250)
egen sblt1m = rowtotal(amountless100 amount100250 amount2501000)

egen entitycounty = group(cert geography)
egen entityyear = group(cert year)

sort entitycounty year

	*Unique bank-county-year
		*Dropping 17 bank county years with >1 observation
		by entitycounty year: gen nobs2 = _N
		drop if nobs2>1
		drop nobs2
		
xtset entitycounty year

gen sbgrowth1m = ln(sblt1m) - ln(L.sblt1m)
gen sbgrowth250k = ln(sblt250k) - ln(L.sblt250k)

sort geography year
drop _merge
merge m:1 geography year using "$LocalData\Demographic.dta"
drop _merge

merge m:1 geography using "$LocalData\Cluster3digit.dta"
drop _merge

save "$LocalData\CRA_RegData.dta", replace

noi disp "Finished loading CRA.dta."

	noi disp "Saving `Data'.dta"
	compress
	
	
	
	save "$LocalData\\`Data'.dta", replace
	save "$LocalData\Archive\\`Data'`CurrentDate'.dta", replace
	}
}
* This runs if no error was returned.
else noi disp "Data already exists."
noi etime
noi disp " "	
	
